<template>
  <div class="infinite-container">
    <mu-list>
      <mu-list-item title="取药方式">
        <span class="list-right-title">
          <selector
            :options="DRUG_METHODS"
            @selectchange="handleRelationChange"
            :defaultValue="drugMethods"
          ></selector>
        </span>
      </mu-list-item>
      <mu-divider />
      <mu-list-item title="收货人" v-if="drugMethods == '2' && address">
        <span slot="right">{{address.consigneeName}} {{address.consigneePhone}}</span>
        <span slot="right" class="t5" @click="changeAddress">&nbsp;&nbsp;&nbsp;更换></span>
      </mu-list-item>
      <mu-divider />

      <mu-list-item title="收货地址" v-if="drugMethods == '2' && address">
        <span
          slot="right"
          style="white-space: normal;max-width: 260px;text-align:right"
        >{{address.province}} {{address.city}} {{address.county}} {{address.township}} {{address.detailedAddress}}</span>
      </mu-list-item>
      <mu-divider />

      <mu-list-item @click="addAddress" v-show="drugMethods == 2 && !address">
        <img slot="left" class="ticon" src="../../assets/fzhis/icon_add.png" />
        <span slot="left">还没有收货地址,请添加收货地址</span>
        <i class="iconfont icon-small-arrow-right t3" slot="right"></i>
      </mu-list-item>
      <mu-divider />
    </mu-list>
    <div class="mt10"></div>
    <div class="item-con">
      <div v-for="(item, index) in allDrugs" :key="index">
        <div class="item-left">
          <div>{{item.drugName}}</div>
          <div>{{item.specification}} * {{item.quantity}}</div>
        </div>
        <div class="item-right">{{item.totalAmount | fixedMoney}}</div>
      </div>
    </div>
    <div class="item-footer">
      <div>
        <div></div>
        <div></div>
        <div>
          <span>共{{allDrugs && allDrugs.length}}件药品</span>
          <span>合计:</span>
          <span>{{totalMoney | fixedMoney}}</span>
        </div>
      </div>
    </div>
    <div class="mt10"></div>

    <CommonList title="配送公司" v-show="drugMethods=='2'">
      <div class="confirm-message" @click="showSelPopup()">
        <span class="mr10">{{selectedExpressCompany}}</span>
        <img src="../../assets/images/arrow_dry.png" alt style="height: 14px" />
      </div>
    </CommonList>

    <CommonList title="配送方式" v-show="drugMethods=='2'">
      <div class="confirm-message" @click="showSelMode = true">
        <span class="mr10">{{selectedExpressMode}}</span>
        <img src="../../assets/images/arrow_dry.png" alt style="height: 14px" />
      </div>
    </CommonList>

    <mu-list v-show="drugMethods=='2'">
      <mu-list-item title="配送费">
        <span slot="right" class="color-price">{{expressFeeCount | fixedMoney}}</span>
      </mu-list-item>
    </mu-list>
    <div class="bottombar">
      <div>
        <span>合计金额:</span>
        <span>{{totalMoney | fixedMoney}}</span>
      </div>
      <div>
        <mu-raised-button
          label="确认下单"
          fullWidth
          primary
          @click="createOrder"
          :disabled="yibaoDisable"
        ></mu-raised-button>
      </div>
    </div>

    <!-- 去人工窗口对话框 -->
    <mu-dialog :open="dialogConfirmOK" title="温馨提示">
      医保患者需到医院自助机或人工缴费窗口缴费
      <mu-raised-button slot="actions" @click="yibaoBack()" primary label="我知道了" fullWidth />
    </mu-dialog>

    <!-- 温馨提示对话框 -->
    <mu-dialog :open="orderSuccessDialog" title="温馨提示">
      下单成功！
      <mu-raised-button slot="actions" @click="gotoPay" primary label="去掌上支付" fullWidth />
    </mu-dialog>

    <popup :show="showSelEmail">
      <div class="bgwhite">
        <div class="popupTitle flex flex_between flex_vcenter">
          <span>请选择物流公司</span>
          <div>
            <mu-flat-button label="确定" primary @click="confirmSel()"></mu-flat-button>
          </div>
        </div>
        <ul class="radios">
          <li v-for="(value, index) in expressCompanyList" :key="index">
            <mu-radio
              :label="value.deliveryModeName"
              :nativeValue="value.deliveryModeCode"
              v-model="companyRadio"
            />
          </li>
        </ul>
      </div>
    </popup>

    <popup :show="showSelMode">
      <div class="bgwhite">
        <div class="popupTitle flex flex_between flex_vcenter">
          <span>请选择配送方式</span>
          <div>
            <mu-flat-button label="确定" primary @click="confirmSelMode()"></mu-flat-button>
          </div>
        </div>
        <ul class="radios">
          <li v-for="(value, index) in modeList" :key="index">
            <mu-radio
              :label="value.payModeName"
              :nativeValue="value.payModeCode"
              v-model="modeRadio"
            />
          </li>
        </ul>
      </div>
    </popup>
  </div>
</template>

<script>
import iconTest from "../../assets/hzssyy/icon_qdqh.png";
import { DRUG_METHODS } from "@/api/const";
import Selector from "@/components/Selector";
import { commonAjaxJson, RESTFUL_API } from "@/api/api";
import popup from "@/components/BsPopup";
import CommonList from "@/components/CommonList";

const MODULE_ID = "016000";
export default {
  data() {
    return {
      DRUG_METHODS,
      familyPerson: JSON.parse(sessionStorage.familyPerson || "{}"),
      drugMethods: "",
      topDeptData: [],
      bottomPopup: true,
      allData: [],
      allDrugs: [],
      totalMoney: 0,
      address: "",
      dialogConfirmOK: false,
      patientCode: "",
      identificationNumber: "",
      orderId: "",
      orderSuccessDialog: false,
      yibaoDisable: false,
      expressCompanyList: [],
      showSelEmail: false,
      selectedExpressCompany: "",
      companyRadio: "",
      expressFeeText: "",
      expressFeeCount: "",
      modeList: [],
      modeRadio: "",
      showSelMode: false,
      selectedExpressMode: ""
    };
  },
  components: { Selector, popup, CommonList },
  beforeRouteEnter(to, from, next) {
    if (from.path.indexOf("/orderHistory/confirmPay") == -1) {
      sessionStorage.setItem("drugMethods", "");
    }
    next(vm => {});
  },
  mounted() {
    if (sessionStorage.getItem("patientMedicalType") == 1) {
      this.dialogConfirmOK = true;
      this.yibaoDisable = true;
    }
    if (sessionStorage.getItem("mailType") == "物流") {
      this.drugMethods = 2;
      // 查询物流公司列表
      this.getExpressCompany();
    }
    let data = this.$store.state.pageData;
    let tempAllDrugs = [];
    let tempTotalMoney = 0;
    let tempIn = [];
    if (data && data.list) {
      data.list.forEach(v => {
        tempAllDrugs = tempAllDrugs.concat(v.drugItems);
        tempTotalMoney += parseFloat(v.totalAmount);
        tempIn.push(`1-${v.recipeId}`);
      });
    }
    this.allDrugs = tempAllDrugs;
    this.totalMoney = tempTotalMoney;
    sessionStorage.setItem("totalDrugMoney", tempTotalMoney);
    this.allData = data;
    this.patientCode = data[0] && data[0].patientCode;
    this.identificationNumber = tempIn.join(",");
    // this.getList();
    if (sessionStorage.drugMethods) {
      this.drugMethods = sessionStorage.drugMethods;
    }
    this.getList();
  },

  activated (to, from, next) {
    this.address = JSON.parse(sessionStorage.selectedAddress || '{}')
  },
  methods: {
    showSelPopup() {
      this.showSelEmail = true;
    },
    confirmSel() {
      this.showSelEmail = false;
      for (let i in this.expressCompanyList) {
        if (this.expressCompanyList[i].deliveryModeCode == this.companyRadio) {
          const currentCompany = this.expressCompanyList[i];
          this.selectedExpressCompany = currentCompany.deliveryModeName;
          this.getExpressMode(currentCompany.deliveryModeCode);
        }
      }
    },
    confirmSelMode() {
      this.showSelMode = false;
      for (let i in this.modeList) {
        if (this.modeList[i].payModeCode == this.modeRadio) {
          const currentCompany = this.modeList[i];
          this.selectedExpressMode = currentCompany.payModeName;
          // this.getExpressMode(currentCompany.payModeCode);
        }
      }

      if (this.modeRadio == 1){
        this.getExpressCost2(1);
      }else{
        this.expressFeeCount = 0
      }
    },

    // 获取快递公司
    getExpressCompany() {
      commonAjaxJson(
        RESTFUL_API.getDeliveryModeCof,
        {
          moduleId: MODULE_ID,
          hospitalCode: sessionStorage.hospitalCode
        },
        true
      ).then(res => {
        if (res.data.code == 200) {
          this.expressCompanyList = res.data.data;

          if (res.data.data.length > 0) {
            const firstCompany = res.data.data[0];
            this.selectedExpressCompany = firstCompany.deliveryModeName;
            // this.expressFeeText = firstCompany.deliveryModeCode == 1 ?  "在线支付" : "到付"
            // this.companyRadio = firstCompany.deliveryModeCode
            if (this.drugMethods == 2) {
              this.getExpressMode(firstCompany.deliveryModeCode);
            }
          }
        }
      });
    },

    //获取快递公司支持的支付方式
    getExpressMode(deliveryModeCode) {
      // 计算快递费用
      let param = {
        deliveryModeCode,
        moduleId: MODULE_ID,
        hospitalCode: sessionStorage.hospitalCode
      };
      commonAjaxJson(RESTFUL_API.getPayModeCof, param, true).then(res => {
        if (res.data.code == 200) {
          this.modeList = res.data.data;
          if (res.data.data.length > 0) {
            const firstMode = res.data.data[0];
            this.selectedExpressMode = firstMode.payModeName;
            this.modeRadio = firstMode.payModeCode;
            //在线支付要查询快递费
            if (firstMode.payModeCode == 1) {
              this.getExpressCost2(firstMode.payModeCode);
            }

            // 在线支付和到付
            if (firstMode.payModeCode == 3) {
              this.modeList = [
                {
                  payModeName: "在线支付",
                  payModeCode: "1"
                },
                {
                  payModeName: "到付",
                  payModeCode: "2"
                }
              ];
              this.selectedExpressMode = "在线支付";
              this.modeRadio = "1";
              this.getExpressCost2(1);
            }
          }
        } else {
          this.$store.commit("UPDATE_TOAST", {
            message: res.data.message
          });
        }
      });
    },

    // 获取在线支付的快递费
    getExpressCost2(expressCompanyCode) {
      // 计算快递费用
      let param = {
        expressCompanyCode: expressCompanyCode
      };
      commonAjaxJson(RESTFUL_API.getExpressCost, param, true).then(res => {
        if (res.data.code == 200) {
          this.expressFeeCount = res.data.data.expressCost;
          this.totalMoney =
            parseInt(res.data.data.expressCost) +
            parseInt(sessionStorage.getItem("totalDrugMoney"));
        } else {
          this.$store.commit("UPDATE_TOAST", {
            message: res.data.message
          });
        }
      });
    },
    yibaoBack() {
      this.dialogConfirmOK = false;
      window.history.go("-1");
    },
    getList() {
      commonAjaxJson(
        RESTFUL_API.getList,
        { userId: sessionStorage.getItem("userId") },
        true
      ).then(res => {
        if (res.data.code == 200) {
          if (res.data.data.length > 0) {
            this.address = res.data.data.filter(v => v.isDefault == 1)[0];
          } else {
            this.address = "";
          }
        }
      });
    },
    changeAddress() {
      this.$router.push({
        path: "/setting/addresses",
        query: { redirect: this.$route.fullPath }
      });
    },
    handleRelationChange(val) {
      this.drugMethods = val;
      if (val == 2) {
        // 快递
        if (!this.address) {
          this.addAddress();
        } else {
          this.getExpressCompany();
        }
      }
    },
    go(path) {
      this.$router.push(path);
    },
    gotoPay() {
      sessionStorage.setItem("drugMethods", this.drugMethods);
      this.orderSuccessDialog = false;
      let param = {
        id: this.orderId,
        patientCode: this.patientCode,
        boilSign: 0,
        consultId: this.$route.query.id,
        takeWay: this.drugMethods,
        province: "",
        city: "",
        county: "",
        township: "",
        detailedAddress: "",
        consigneeName: "",
        consigneePhone: "",
        boilSign: 0,
        expressCompanyCode: "",
        expressFee: "",
        freightCollect: ""
      };
      if (this.drugMethods == "2") {
        // 物流配送
        param.province = this.address.province;
        param.city = this.address.city;
        param.county = this.address.county;
        param.township = this.address.township;
        param.detailedAddress = this.address.detailedAddress;
        param.consigneeName = this.address.consigneeName;
        param.consigneePhone = this.address.consigneePhone;
        param.expressCompanyCode = this.companyRadio;
        param.expressFee = this.expressFeeCount;
        param.freightCollect = this.expressFeeText == "到付" ? 1 : 0;
      }
      this.$router.push({
        path: `/orderHistory/confirmPay`,
        query: param
      });
    },
    addAddress() {
      this.$router.push({
        path: "/setting/edit-address",
        query: {
          action: "add",
          redirect: this.$route.path
        }
      });
    },
    createOrder() {
      if (!this.drugMethods) {
        this.$store.commit("UPDATE_TOAST", {
          message: "请选择取药方式"
        });
        return;
      }
      if (this.drugMethods == "2" && !this.address) {
        this.$store.commit("UPDATE_TOAST", {
          message: "请添加或选择配送地址"
        });
        return;
      }
      let params = {
        takeType: this.drugMethods,
        consultId: "",
        // visitNo: JSON.parse(sessionStorage.getItem('medicalToBuyInfo')).list[0].visitNo,
        patientCode: this.patientCode,
        orderAmount: this.totalMoney,
        identificationNumber: this.identificationNumber,
        boilSign: 0
      };
      if (!this.$route.query.id || this.$route.query.id == "undefined") {
        params.consultId = sessionStorage.getItem("medicalToBuyCid");
      } else {
        params.consultId = this.$route.query.id;
      }
      if (this.drugMethods == "2") {
        params.expressOrder = {
          tel: this.address.consigneePhone,
          reciverName: this.address.consigneeName,
          freightCollect: 0,
          reciverProvince: this.address.province,
          reciverCity: this.address.city,
          reciverCounty: this.address.county,
          reciverStreet: this.address.township,
          address: this.address.detailedAddress
        };
      }
      
      commonAjaxJson(RESTFUL_API.commitRecipePay, params, true).then(res => {
        
        if (res.data.code == 200) {
          // todo
          this.orderId = res.data.data.paymentOrderId;
          this.orderSuccessDialog = true;
        } else {
          this.$store.commit("UPDATE_TOAST", {
            message: res.data.message
          });
        }
      });
    }
  }
};
</script>

<style scoped lang="less">
@import "../../common/css/flex.css";
@import "../../common/css/component";
.infinite-container {
  @{deep} .mu-list {
    background: #fff;
  }
  @{deep} .mu-item-title {
    font-size: 14px;
    color: #666;
  }
  @{deep} .mu-item-right {
    font-size: 14px;
    color: #333;
  }
  @{deep} .mu-item.show-left {
    padding-left: 42px;
  }
  @{deep} .mu-item-content {
    padding-left: 5px;
  }
  @{deep} .mu-item {
    min-height: 44px;
  }
  @{deep} .mu-item-left {
    width: auto;
  }
}

.tbar {
  height: 35px;
  line-height: 35px;
  background: #f0f0f0;
  color: #666;
  padding-left: 15px;
}

.item-con {
  border-bottom: 1px solid #e8e8e8;
  border-top: 1px solid #e8e8e8;
  background: #fff;
  padding: 15px 15px 0px 15px;
  font-size: 14px;
  color: #333;
  > div {
    margin-bottom: 10px;
  }
  > div {
    width: 100%;
    position: relative;
    display: table;
    > div {
      display: table-cell;
    }
  }
}

.item-footer {
  width: 100%;
  padding-left: 15px;
  overflow: hidden;
  background: #fff;
  border-bottom: 1px solid #efefef;
  img {
    width: 14px;
    height: 14px;
  }
  > div {
    width: 100%;
    height: 40px;
    display: table;
    font-size: 14px;
    > div {
      display: table-cell;
      vertical-align: middle;
    }
    > div:first-child {
      line-height: 0;
    }
    > div:nth-child(3) {
      padding-right: 15px;
      text-align: right;
      color: #ff6600;
      > span:first-child {
        color: #666;
      }
    }
    > div:nth-child(4) {
      width: 75px;
      padding-right: 15px;
      text-align: right;
      white-space: nowrap;
    }
  }
}

.item-right {
  text-align: right;
  white-space: nowrap;
}

.item-left {
  > div:nth-child(2) {
    color: #999;
  }
}

.choseicon {
  width: 20px;
  height: 20px;
  margin-left: 10px;
}

.ticon {
  width: 20px;
  height: 20px;
  margin-right: 10px;
  margin-left: 5px;
}

.bottombar {
  position: absolute;
  height: 49px;
  left: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #efefef;
  background: #fff;
  overflow: hidden;
  > div:first-child {
    font-size: 14px;
    float: left;
    width: 100%;
    margin-left: -100px;
    line-height: 49px;
    padding-left: 115px;
    > span {
      color: #333;
      line-height: 49px;
    }
    > span:last-child {
      color: #ff6600;
      font-size: 18px;
    }
  }
  > div:nth-child(2) {
    width: 100px;
    height: 100%;
    float: right;
    .mu-raised-button-primary {
      width: 100%;
      height: 100%;
      border-radius: 0;
    }
  }
}
.popupTitle {
  padding: 10px;
  > span {
    font-size: 16px;
  }
}
.radios {
  > li {
    padding: 10px;
  }
}
</style>
